<?php
require_once 'config.php';
$timerData = getTimerData();
$currentTime = $timerData['elapsed_time'];
if ($timerData['is_running'] && $timerData['start_time']) {
    $currentTime += (time() - $timerData['start_time']);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时计时器看板 - 100ms刷新</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Arial', sans-serif;
            height: 100vh;
            background: linear-gradient(135deg, #0f172a, #1e293b);
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            color: white;
        }
        .dashboard {
            width: 95vw;
            height: 95vh;
            display: grid;
            grid-template-rows: 1fr 2fr;
            gap: 20px;
            padding: 20px;
        }
        .timer-container {
            background: rgba(0, 0, 0, 0.8);
            border-radius: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            border: 3px solid #00ffcc;
            box-shadow: 0 0 40px rgba(0, 255, 204, 0.4);
            overflow: hidden;
        }
        .timer {
            font-size: 12vw;
            font-family: 'Courier New', monospace;
            font-weight: bold;
            color: #00ffcc;
            text-shadow: 0 0 30px #00ffcc, 0 0 60px #00ffcc;
            letter-spacing: 2px;
        }
        .timer-milliseconds {
            font-size: 4vw;
            color: #00ff99;
            margin-left: 10px;
            opacity: 0.8;
        }
        .status-light {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            transition: all 0.3s ease;
        }
        .status-running {
            background: #00ff00;
            box-shadow: 0 0 20px #00ff00, 0 0 40px #00ff00;
            animation: pulse 0.5s infinite;
        }
        .status-stopped {
            background: #ff0000;
            box-shadow: 0 0 20px #ff0000, 0 0 40px #ff0000;
        }
        .scores-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .score-panel {
            border-radius: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        .blue-panel {
            background: linear-gradient(135deg, #1e40af, #3b82f6);
            border: 3px solid #3b82f6;
            box-shadow: 0 0 40px rgba(59, 130, 246, 0.4);
        }
        .red-panel {
            background: linear-gradient(135deg, #b91c1c, #ef4444);
            border: 3px solid #ef4444;
            box-shadow: 0 0 40px rgba(239, 68, 68, 0.4);
        }
        .score {
            font-size: 15vw;
            font-weight: bold;
            text-shadow: 0 2px 30px rgba(0, 0, 0, 0.7);
            transition: all 0.2s ease;
        }
        .refresh-info {
            position: absolute;
            bottom: 15px;
            right: 15px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.6);
            background: rgba(0, 0, 0, 0.3);
            padding: 5px 10px;
            border-radius: 15px;
        }
        .update-indicator {
            position: absolute;
            top: 15px;
            left: 15px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #00ff00;
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .updating {
            animation: scoreUpdate 0.2s ease;
        }
        .data-updating {
            opacity: 1 !important;
        }
        
        @keyframes pulse {
            0%, 100% { 
                opacity: 1;
                transform: scale(1);
            }
            50% { 
                opacity: 0.7;
                transform: scale(1.1);
            }
        }
        
        @keyframes scoreUpdate {
            0% { 
                transform: scale(1);
                text-shadow: 0 2px 30px rgba(0, 0, 0, 0.7);
            }
            50% { 
                transform: scale(1.15);
                text-shadow: 0 5px 40px rgba(255, 255, 255, 0.3);
            }
            100% { 
                transform: scale(1);
                text-shadow: 0 2px 30px rgba(0, 0, 0, 0.7);
            }
        }
        
        @keyframes glow {
            0%, 100% { box-shadow: 0 0 40px currentColor; }
            50% { box-shadow: 0 0 60px currentColor; }
        }
        
        .timer-glow {
            animation: glow 2s ease-in-out infinite;
        }

        @media (max-width: 768px) {
            .timer { font-size: 15vw; }
            .timer-milliseconds { font-size: 5vw; }
            .score { font-size: 20vw; }
            .dashboard { 
                grid-template-rows: 1fr 1fr; 
                padding: 15px; 
                gap: 15px; 
            }
            .refresh-info { font-size: 12px; }
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <!-- 计时器区域 -->
        <div class="timer-container">
            <div class="timer" id="timer"><?php echo gmdate("H:i:s", $currentTime); ?></div>
            <span class="timer-milliseconds" id="milliseconds">.00</span>
            <div class="status-light <?php echo $timerData['is_running'] ? 'status-running' : 'status-stopped'; ?>" id="status-light"></div>
            <div class="update-indicator" id="timer-update-indicator"></div>
        </div>
        
        <!-- 分数区域 -->
        <div class="scores-container">
            <!-- 蓝方分数 -->
            <div class="score-panel blue-panel">
                <div class="score" id="blue-score"><?php echo $timerData['blue_score']; ?></div>
                <div class="refresh-info">100ms刷新</div>
                <div class="update-indicator" id="blue-update-indicator"></div>
            </div>
            
            <!-- 红方分数 -->
            <div class="score-panel red-panel">
                <div class="score" id="red-score"><?php echo $timerData['red_score']; ?></div>
                <div class="refresh-info">100ms刷新</div>
                <div class="update-indicator" id="red-update-indicator"></div>
            </div>
        </div>
    </div>

    <script>
        const API_URL = 'api.php';
        let currentState = {
            elapsed_time: <?php echo $currentTime; ?>,
            is_running: <?php echo $timerData['is_running'] ? 'true' : 'false'; ?>,
            blue_score: <?php echo $timerData['blue_score']; ?>,
            red_score: <?php echo $timerData['red_score']; ?>,
            last_server_time: <?php echo $currentTime; ?>,
            last_update: Date.now()
        };

        let timerInterval = null;
        let dataRefreshInterval = null;
        let localTimerStart = null;
        let lastDataFetch = 0;
        let fetchCount = 0;
        let lastServerUpdate = Date.now();

        // 页面加载初始化
        window.addEventListener('load', function() {
            console.log('高频看板已启动 - 100ms刷新');
            
            // 初始化计时器
            if (currentState.is_running) {
                startLocalTimer();
            } else {
                updateTimerDisplay(currentState.elapsed_time);
            }
            
            // 立即获取一次数据
            fetchData();
            
            // 设置100ms数据刷新
            dataRefreshInterval = setInterval(fetchData, 100);
            
            // 设置10ms的UI更新（更流畅的计时器显示）
            setInterval(updateUITimer, 10);
        });

        // 获取数据函数 - 100ms间隔
        function fetchData() {
            const now = Date.now();
            
            // 防止过于频繁的请求，确保至少50ms间隔
            if (now - lastDataFetch < 50) {
                return;
            }
            
            lastDataFetch = now;
            fetchCount++;

            fetch(API_URL + '?action=get_data&t=' + now)
                .then(response => {
                    if (!response.ok) throw new Error('网络错误: ' + response.status);
                    return response.json();
                })
                .then(data => {
                    if (data?.success) {
                        lastServerUpdate = Date.now();
                        updateDataIndicators();
                        processServerData(data.data);
                    }
                })
                .catch(error => {
                    console.debug('数据获取失败:', error);
                    updateConnectionStatus(false);
                });
        }

        // 处理服务器返回的数据
        function processServerData(data) {
            // 更新连接状态
            updateConnectionStatus(true);
            
            // 检查状态变化
            if (data.is_running !== currentState.is_running) {
                currentState.is_running = data.is_running;
                updateTimerStatus(data.is_running);
            }
            
            // 更新分数
            if (data.blue_score !== currentState.blue_score) {
                updateScore('blue-score', data.blue_score, 'blue-update-indicator');
                currentState.blue_score = data.blue_score;
            }
            
            if (data.red_score !== currentState.red_score) {
                updateScore('red-score', data.red_score, 'red-update-indicator');
                currentState.red_score = data.red_score;
            }
            
            // 更新服务器时间基准
            if (data.elapsed_time !== currentState.last_server_time) {
                currentState.last_server_time = data.elapsed_time;
                currentState.last_update = Date.now();
                
                if (currentState.is_running) {
                    // 如果计时器正在运行，重新校准本地计时器
                    if (timerInterval) {
                        clearInterval(timerInterval);
                    }
                    startLocalTimer();
                } else {
                    // 如果计时器停止，直接更新显示
                    updateTimerDisplay(data.elapsed_time);
                }
            }
        }

        // 启动本地计时器
        function startLocalTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
            }
            
            localTimerStart = Date.now() - (currentState.last_server_time * 1000);
            updateUITimer(); // 立即更新一次
        }

        // UI计时器更新 - 10ms间隔（更流畅）
        function updateUITimer() {
            if (currentState.is_running && localTimerStart) {
                const elapsedMilliseconds = Date.now() - localTimerStart;
                const elapsedSeconds = elapsedMilliseconds / 1000;
                
                updateTimerDisplay(elapsedSeconds);
                updateMillisecondsDisplay(elapsedMilliseconds);
            }
        }

        // 更新计时器显示
        function updateTimerDisplay(seconds) {
            const totalSeconds = Math.floor(seconds);
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const secs = totalSeconds % 60;
            
            document.getElementById('timer').textContent = 
                `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }

        // 更新毫秒显示
        function updateMillisecondsDisplay(milliseconds) {
            const ms = Math.floor((milliseconds % 1000) / 10); // 显示到10毫秒精度
            document.getElementById('milliseconds').textContent = '.' + ms.toString().padStart(2, '0');
        }

        // 更新计时器状态
        function updateTimerStatus(isRunning) {
            const statusLight = document.getElementById('status-light');
            statusLight.className = isRunning ? 'status-light status-running' : 'status-light status-stopped';
            
            if (isRunning) {
                startLocalTimer();
            } else {
                if (timerInterval) {
                    clearInterval(timerInterval);
                    timerInterval = null;
                }
                updateTimerDisplay(currentState.last_server_time);
                document.getElementById('milliseconds').textContent = '.00';
            }
        }

        // 更新分数显示
        function updateScore(elementId, newScore, indicatorId) {
            const element = document.getElementById(elementId);
            const indicator = document.getElementById(indicatorId);
            
            if (element.textContent !== newScore.toString()) {
                element.textContent = newScore;
                element.classList.add('updating');
                
                // 显示更新指示器
                indicator.classList.add('data-updating');
                
                setTimeout(() => {
                    element.classList.remove('updating');
                    indicator.classList.remove('data-updating');
                }, 200);
            }
        }

        // 更新数据更新指示器
        function updateDataIndicators() {
            const indicator = document.getElementById('timer-update-indicator');
            indicator.classList.add('data-updating');
            
            setTimeout(() => {
                indicator.classList.remove('data-updating');
            }, 50);
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            // 这里可以添加连接状态显示逻辑
            // 目前通过更新指示器来显示数据流动
        }

        // 清理定时器
        window.addEventListener('beforeunload', function() {
            if (timerInterval) clearInterval(timerInterval);
            if (dataRefreshInterval) clearInterval(dataRefreshInterval);
        });

        // 性能监控（可选）
        setInterval(() => {
            const now = Date.now();
            const timeSinceLastUpdate = now - lastServerUpdate;
            if (timeSinceLastUpdate > 1000) {
                console.warn('服务器数据更新延迟:', timeSinceLastUpdate + 'ms');
            }
        }, 1000);

    </script>
</body>
</html>